package cn.example.vip.mall.canal.listener;


import cn.example.vip.mall.goods.entity.Sku;
import cn.example.vip.mall.goods.feign.NginxCacheFeign;
import cn.example.vip.mall.page.feign.PageFeign;
import cn.example.vip.mall.search.entity.SkuEs;
import cn.example.vip.mall.search.feign.SkuSearchFeign;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

@Component
@CanalTable("sku")
public class SkuHandler implements EntryHandler<Sku> {
	@Autowired
	private SkuSearchFeign skuSearchFeign;
	@Autowired
	private PageFeign pageFeign;
	@Autowired
	NginxCacheFeign nginxCacheFeign;
	
	@SneakyThrows
	@Override
	public void insert(Sku sku) {
		System.out.println("插入索引");
		if(sku.getStatus() == 1){
			System.out.println("添加索引");
			skuSearchFeign.add(JSON.parseObject(JSON.toJSONString(sku), SkuEs.class));
		}
		// 调用商品详情页生成(判断是否被删除)
		if(sku.getStatus() != 3){
			pageFeign.html(sku.getSpuId());
		}
	}
	
	@SneakyThrows
	@Override
	public void update(Sku before, Sku after) {
//		System.out.println("--------更新索引" + before + "," + after);
		if (after.getStatus() == 2) {
			System.out.println("--------删除索引");
			// 删除索引
			skuSearchFeign.del(after.getId());
		} else {
//			System.out.println("--------添加索引" + JSON.toJSONString(after) + "," + JSON.parseObject(JSON.toJSONString(after), SkuEs.class));
			// 更新索引
			skuSearchFeign.add(JSON.parseObject(JSON.toJSONString(after), SkuEs.class));
		}
		
		// 调用商品详情页生成(判断是否被删除)
		if(after.getStatus() != 3){
			pageFeign.html(after.getSpuId());
		}
	}
	
	@SneakyThrows
	@Override
	public void delete(Sku sku) {
		System.out.println("--------删除索引");
		skuSearchFeign.del(sku.getId());
		// 删除商品详情页
		if(sku.getStatus() == 3){
			pageFeign.delHtml(sku.getSpuId());
		}
	}
}
